/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation
**
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/

#include <asshdalarm.h>
#include <asclisession.h>

#include "alarmserver_symbian.h"

/*!
 * Symbian static constructor.
 */
AlarmServerExPrivate* AlarmServerExPrivate::NewL(AlarmServerEx *aPublicAPI)
{
    AlarmServerExPrivate* self = new (ELeave) AlarmServerExPrivate(aPublicAPI);
    CleanupStack::PushL(self);
    self->ConstructL();
    CleanupStack::Pop(self);
    return self;
}

/*!
 * Symbian second stage constructor
 */
void AlarmServerExPrivate::ConstructL()
{
    // connect to the alarm server
    User::LeaveIfError(iAlarmServerSession.Connect());
}

/*!
 * Private constructor - initialise the pointer to the public API class
 * and make this high priority for scheduling.
 */ 
AlarmServerExPrivate::AlarmServerExPrivate(AlarmServerEx *aPublicAPI):iPublic(aPublicAPI)
{

}

AlarmServerExPrivate::~AlarmServerExPrivate()
{
    // Cancel any outstanding requests before this object is destroyed.
    // This destructor cannot leave - so trap any problems here.

    iAlarmServerSession.Close();
}

/*!
 * Adds fixed alarm.
 */
void AlarmServerExPrivate::AddFixedAlarm()
{
    // Create an alarm.
    TASShdAlarm alarm;

    // Add alarm message.
    _LIT(KAlarmMessage, "This is a fixed alarm");
    alarm.Message() = KAlarmMessage;

    // Add alarm sound.
    _LIT(KAlarmSound, "Chimes");
    alarm.SoundName() = KAlarmSound;

    // Alarm occurs once.
    alarm.RepeatDefinition() = EAlarmRepeatDefintionRepeatOnce;

    TTime time;

    // Time is set in UTC for a fixed alarm
    time.UniversalTime();

    // Set alarm to expire in 10 seconds.
    time += TTimeIntervalSeconds(10);
    alarm.SetUtcNextDueTime(time);

    // WriteUserData capability is required to add an alarm
    User::LeaveIfError(iAlarmServerSession.AlarmAdd(alarm));

    // Alarm id value is emitted by the signal.
    QString alarmId;
    alarmId.setNum(int(alarm.Id()));
    emit iPublic->alarmAdded(alarmId);
}

/*!
 * Adds floating alarm.
 */
void AlarmServerExPrivate::AddFloatingAlarm()
{
    // Create an alarm.
    TASShdAlarm alarm;

    // Alarm occurs once, today. This is the default.
    alarm.RepeatDefinition() = EAlarmRepeatDefintionRepeatOnce;

    // Add alarm message.
    _LIT(KAlarmMessage,"This is a floating alarm.");
    alarm.Message() = KAlarmMessage;

    // Add alarm sound.
    _LIT(KAlarmSound, "Chimes");
    alarm.SoundName() = KAlarmSound;

    // Get the local time and set it as the alarm's due time
    alarm.NextDueTime().HomeTime();

    // Set alarm to expire in 10 seconds.
    alarm.NextDueTime() += TTimeIntervalSeconds(10);
    User::LeaveIfError(iAlarmServerSession.AlarmAdd(alarm));

    // Alarm id value is emitted by the signal.
    QString alarmId;
    alarmId.setNum(int(alarm.Id()));
    emit iPublic->alarmAdded(alarmId);
}

/*!
 * Converts TDateTime to string.
 */
QString AlarmServerExPrivate::ConvertToString(TDateTime time)
{
    QString displayText;
    displayText.append("Date: ");
    QString day;
    day.setNum((int)time.Day());
    displayText.append(day);
    displayText.append("-");
    QString month;
    month.setNum((int)time.Month());
    displayText.append(month);
    displayText.append("-");
    QString year;
    year.setNum((int)time.Year());
    displayText.append(year);
    displayText.append("\n");
    displayText.append("Time: ");
    QString hour;
    hour.setNum((int)time.Hour());
    displayText.append(hour);
    displayText.append(":");
    QString minute;
    minute.setNum((int)time.Minute());
    displayText.append(minute);
    displayText.append(":");
    QString second;
    second.setNum((int)time.Second());
    displayText.append(second);

    return displayText;
}

/*!
 * Get the alarm details.
 */
QString AlarmServerExPrivate::GetAlarmDetails(QString alarmId)
{
    TASShdAlarm alarmInfo;

    // Convert QString to TInt, to get the alarmId
    TInt alarm = alarmId.toInt();

    // Get the alarm details.
    iAlarmServerSession.GetAlarmDetails(alarm,alarmInfo);
    QString alarmDetails;
    alarmDetails.append("\nAlarm ID:\n");
    alarmDetails.append(alarmId);

    // Alarm state information.
    alarmDetails.append("\n\nAlarm State:\n");
    TInt state = alarmInfo.State();
    if(state == EAlarmStateInPreparation)
        alarmDetails.append("Alarm State in preparation.\n");
    else if(state == EAlarmStateQueued)
        alarmDetails.append("Alarm State Queued.\n");
    else if(state == EAlarmStateSnoozed)
        alarmDetails.append("Alarm State Snoozed.\n");
    else if(state == EAlarmStateWaitingToNotify)
        alarmDetails.append("Alarm State waiting to notify.\n");
    else if(state == EAlarmStateNotifying)
        alarmDetails.append("Alarm State notifying.\n");
    else if(state == EAlarmStateNotified)
        alarmDetails.append("Alarm State notified.\n");

    // Alarm next due time.
    alarmDetails.append("\nAlarm Due time:\n");
    TDateTime dueTime = alarmInfo.NextDueTime().DateTime();
    QString displayText = ConvertToString(dueTime);
    alarmDetails.append(displayText);

    // Alarm original time.
    alarmDetails.append("\n\nOriginal time:\n");
    TDateTime originalTime = alarmInfo.OriginalExpiryTime().DateTime();
    displayText = ConvertToString(originalTime);
    alarmDetails.append(displayText);

    alarmDetails.append("\n\nAlarm Message :\n");
    alarmDetails.append(QString::fromUtf16(alarmInfo.Message().Ptr(),
                                           alarmInfo.Message().Length()));
    alarmDetails.append("\n\nSound Name :\n");
    alarmDetails.append(QString::fromUtf16(alarmInfo.SoundName().Ptr(),
                                           alarmInfo.SoundName().Length()));

    return alarmDetails;
}

